import React, { useState, useRef, useEffect } from "react";
import {
  Button,
  Card,
  Checkbox,
  Form,
  Input,
  Radio,
  Select,
  Space,
  Switch,
  Tag,
  Tooltip,
} from "antd";
import "./index.scss";
import lodash from "lodash";
import { selectItemList } from "./util";
import {
  MinusCircleOutlined,
  PlusOutlined,
  QuestionCircleOutlined,
} from "@ant-design/icons";
// import { searchSite } from "../../api/test";
const { Option } = Select;

// 选中的数据列表
let selectedRowKeysList: any = [];
export default () => {
  const actionRef = useRef();
  const ruleTreeRef = useRef();
  const actionRefTable = useRef();
  const actionRefEvaluateTable = useRef();
  const [showWhich, setshowWhich] = useState("SPI");
  const [businessDomainList, setBusinessDomainList] = useState([]);
  const [businessSeachList, setBusinessSeachList] = useState([]);
  const [selectLoadingSelect, setselectLoadingSelect] = useState(false);
  const [selectChilenNotice, setSelectChilenNotice] = useState<any>([]);
  const [form] = Form.useForm();
  const [proForm] = Form.useForm();
  const [open, setOpen] = useState(false);
  const [openChangeValue, setOpenChangeValue] = useState<any>("");
  const [idChangeRow, setIdChangeRow] = useState<any>("");
  const [testSelectListFirst, settestSelectListFirst] = useState([]);
  const [platFormList, setPlatFormList] = useState(selectItemList);
  // 浏览

  const [selectDate, setselectDate] = useState([
    {
      _id: "66f916dab657ca5b6cfd1d29",
      id: "800001",
      siteName: "主站",
      siteCode: "main_site",
      description: "sigma 管理平台",
      platformId: "20191030002450240000000000XX00AZA3YG",
      servicePlatform: "sigmaboss",
      platformOwners: null,
      qaOwners: null,
      sreOwners: null,
      gatewayServiceList: [
        {
          name: "rtyui",
        },
      ],
      gatewayControlLevel: 0,
      autotestServiceList: [],
      autotestControlLevel: 0,
      avatar: "ae40ef9ce177e794f2886b2172bfb40b",
    },
    {
      _id: "66fa1c857809b486f26094e8",
      id: "80002",
      siteName: "上千万",
      siteCode: "123ws",
      description: "撒出现",
      gatewayServiceList: [],
      autotestServiceList: [],
      __v: 0,
    },
    {
      _id: "66fa43871b3fdce210e38cb6",
      id: "80003",
      siteName: "主站线下",
      siteCode: "123ws1",
      description: "撒出现",
      gatewayServiceList: [],
      autotestServiceList: [],
      __v: 0,
    },
    {
      _id: "6719b53fd76afd51790d998d",
      id: "1",
      siteName: "测试",
      siteCode: "wqqe",
      description: "123",
      gatewayServiceList: [],
      autotestServiceList: [],
      avatar: "f44841524fa34e068a992b07be41501f",
      __v: 0,
    },
    {
      _id: "6719b556d76afd51790d9991",
      id: "122",
      siteName: "环境",
      siteCode: "21",
      description: "2333",
      gatewayServiceList: [],
      autotestServiceList: [],
      avatar: "c85570545fd1d955b602b3c826a8f01b",
      __v: 0,
    },
  ]);
  const [drawOpen, setDrawOpen] = useState(false);
  console.log("页面更新了！！！！！！");
  const searchFun = (key: any, platFormList: any) => {
    let srrList: any = [];
    platFormList.map((item: any) => {
      if (item?.id === form.getFieldValue("users")[key]?.first?.value) {
        srrList = item?.gatewayServiceList;
      }
    });
    return srrList;
  };

  // 掉接口查询数据
  const UserChangeSelect = lodash.debounce(async (value: any) => {
    console.log(value, "value");

    // searchSite( { currentPage:1, pageSize:10 },
    //   { siteName: value}).then(res=>{
    //   console.log(res,"res");
    //   settestSelectListFirst(res?.data?.data||[])
    // }
    // )
  }, 1000);
  return (
    <>
      <Form
        name="basic"
        // layout="vertical"
        disabled={openChangeValue == "view"}
        form={form}
        onFinish={(values) => {
          console.log("Success:", values);
        }}

        // autoComplete="off"
      >
        <p>1. 通过form提供的方法去控制显示和隐藏，不会触发页面渲染【推荐】</p>
        <Form.Item
          label="模式选择"
          name="mode"
          initialValue={"SPI"}
          rules={[{ required: true, message: "请选择模式" }]}
        >
          <Select
            placeholder="请选择模式"
            options={[
              { label: "SPI", value: "SPI" },
              { label: "验收任务", value: "JOB" },
              { label: "人工确认", value: "MANUAL" },
            ]}
            onChange={(val) => {
              form.setFieldsValue({
                uniqueId: null,
                overTime: null,
                task: [],
                properConfirm: [],
                peoperList: [{}],
              });
            }}
          />
        </Form.Item>
        <Card size="small" title="任务配置" style={{ width: 600 }}>
          {/* 当运行模式为：SPI */}
          <Form.Item
            noStyle
            shouldUpdate={(prevValues, currentValues) =>
              prevValues.mode !== currentValues.mode
            }
          >
            {({ getFieldValue }) =>
              getFieldValue("mode") === "SPI" ? (
                <>
                  <Form.Item
                    name="uniqueId"
                    label="Unique ID"
                    // rules={[{ required: true }]}
                  >
                    <Input placeholder="请输入Unique ID" />
                  </Form.Item>
                </>
              ) : null
            }
          </Form.Item>
          {/* 当运行模式为：验收任务 */}
          <Form.Item
            noStyle
            shouldUpdate={(prevValues, currentValues) =>
              prevValues.mode !== currentValues.mode
            }
          >
            {({ getFieldValue }) =>
              getFieldValue("mode") === "JOB" ? (
                <>
                  <div style={{ position: "relative" }}>
                    <Form.Item label="验收任务" name="task" required={false}>
                      <Input placeholder="请输入验收任务" />
                    </Form.Item>
                  </div>
                </>
              ) : null
            }
          </Form.Item>
          {/* 当运行模式为：人工确认 */}
          <Form.Item
            noStyle
            shouldUpdate={(prevValues, currentValues) =>
              prevValues.mode !== currentValues.mode
            }
          >
            {({ getFieldValue }) =>
              getFieldValue("mode") === "MANUAL" ? (
                <>
                  <Form.Item
                    label="人工确认"
                    name="properConfirm"
                    required={false}
                  >
                    <Input placeholder="人工确认" />
                  </Form.Item>
                </>
              ) : null
            }
          </Form.Item>
        </Card>
        <p>2. 通过变量去控制显示和隐藏，会触发页面渲染【不推荐】</p>

        <Form.Item
          label="模式选择"
          name="mode1"
          initialValue={"SPI"}
          // rules={[{ required: true, message: "请选择模式" }]}
        >
          <Select
            placeholder="请选择模式"
            options={[
              { label: "SPI", value: "SPI" },
              { label: "验收任务", value: "JOB" },
              { label: "人工确认", value: "MANUAL" },
            ]}
            onChange={(val) => {
              setshowWhich(val);
            }}
          />
        </Form.Item>
        <Card size="small" title="任务配置" style={{ width: 600 }}>
          {/* 当运行模式为：SPI */}
          {showWhich === "SPI" && (
            <Form.Item
              name="uniqueId1"
              label="Unique ID"
              // rules={[{ required: true }]}
            >
              <Input placeholder="请输入Unique ID1" />
            </Form.Item>
          )}
          {showWhich === "JOB" && (
            <Form.Item label="验收任务" name="task" required={false}>
              <Input placeholder="请输入验收任务" />{" "}
            </Form.Item>
          )}
          {showWhich === "MANUAL" && (
            <Form.Item label="人工确认" name="properConfirm" required={false}>
              <Input placeholder="人工确认" />
            </Form.Item>
          )}
        </Card>

        <p>3. 开关Switch和复选框在表单中使用注意事项！！！</p>
        <Form.Item
          label="是否开启"
          name="switch1"
          initialValue={true}
          // valuePropName="checked"
        >
          <Switch />
        </Form.Item>
        <Form.Item
          label="性别"
          name="checkbox"
          initialValue={["male"]}
          // valuePropName="checked"
        >
          <Checkbox.Group
            options={[
              { label: "男", value: "male" },
              { label: "女", value: "woman" },
            ]}
          />
        </Form.Item>
        <Button
          onClick={() => {
            form.setFieldsValue({
              switch1: false,
              // checkbox: ["woman"],
            });
          }}
        >
          点我通过form.setFieldsValues回显
        </Button>
        <Tooltip
          title={
            <p>
              Form.Item 默认绑定值属性到 value 上，而 Switch、Checkbox
              等组件的值属性为 checked。你可以通过 valuePropName
              来修改绑定的值属性。】
            </p>
          }
        >
          <Button>点我查看原因</Button>
        </Tooltip>

        <p>4. form里面的下拉选项如何包裹数据的每一项【两种写法】</p>
        <Form.Item label="第一种" name="selectOne">
          <Select
            labelInValue
            onChange={(val, option) => {
              // 在option里面可以拿到-【items】的值
              console.log(val, option, "val");
            }}
          >
            {selectDate.map((item, index) => {
              return (
                <Select.Option
                  // value={item.siteCode}
                  value={JSON.stringify(item)}
                  key={index}
                  items={item}
                >
                  {item.siteName}
                </Select.Option>
              );
            })}
          </Select>
        </Form.Item>
        <Form.Item label="第二种" name="selectTwo">
          <Select
            labelInValue
            options={selectDate.map((item, index) => {
              return {
                label: item.siteName,
                value: item.siteCode,
                key: index,
                items: item,
                lll: "4567890",
              };
            })}
            onChange={(val, option) => {
              // 在option里面可以拿到-【items】的值
              console.log(val, option, "val");
              form.setFieldValue("selectTwo", { ...val, items: option?.items });
            }}
          />
        </Form.Item>
        <p>5.如果是在formlist里面，用变量存储就不合适了？该怎么获取呢？</p>
        <Form.List name="selectList" initialValue={[{}]}>
          {(fields, { add, remove }) => (
            <>
              {fields.map(({ key, name, ...restField }) => {
                return (
                  <Space
                    key={key}
                    style={{ display: "flex", marginBottom: 8 }}
                    align="baseline"
                  >
                    <Form.Item {...restField} name={[name]}>
                      <Select
                        // mode="multiple"
                        // allowClear
                        // showSearch
                        labelInValue
                        // filterOption={false}
                        // optionLabelProp="label"
                        onChange={(value, items) => {
                          console.log(value, items, "value", name);
                          form.setFieldValue(
                            // ["selectList",name],item
                            "selectList",
                            form
                              .getFieldValue("selectList")
                              .map((item: any, idx: any) => {
                                return {
                                  ...item,
                                  items:
                                    item?.value === value?.value
                                      ? items.items
                                      : item?.items,
                                };
                              })
                          );
                        }}
                        style={{ width: "300px" }}
                        placeholder="请选择平台"
                      >
                        {selectDate.map((item, index) => {
                          return (
                            <Option
                              value={item.siteCode}
                              label={item.siteName}
                              // value={JSON.stringify(item)}
                              key={index}
                              items={item}
                            >
                              {item.siteName}
                            </Option>
                          );
                        })}
                      </Select>
                    </Form.Item>

                    <MinusCircleOutlined onClick={() => remove(name)} />
                  </Space>
                );
              })}
              <Form.Item>
                <Button
                  type="dashed"
                  onClick={() => add()}
                  block
                  icon={<PlusOutlined />}
                >
                  新增一项
                </Button>
              </Form.Item>
            </>
          )}
        </Form.List>
        <p>6. formList中的关联表单</p>

        <p>【固定数据】</p>
        <Form.List
          name="users"
          initialValue={[
            {
              first: 1000002,
              last: [{ value: [1200064], label: "应用批次发布" }],
            },
          ]}
        >
          {(fields, { add, remove }) => (
            <>
              {fields.map(({ key, name, ...restField }) => {
                // console.log({ key, name }, "oooooo");

                return (
                  <Space
                    key={key}
                    style={{ display: "flex", marginBottom: 8 }}
                    align="baseline"
                  >
                    <Form.Item
                      {...restField}
                      name={[name, "first"]}
                      rules={[{ required: true, message: "请选择" }]}
                    >
                      <Select
                        // mode="multiple"
                        allowClear
                        showSearch
                        labelInValue
                        filterOption={false}
                        optionLabelProp="label"
                        onChange={(value, item) => {
                          console.log("tyui", key, name);

                          // console.log('HHHHHHHHHHHHH', form.getFieldValue(["users"][key])["last"])

                          // form.setFieldValue({users}.[key],[{name:1,version:"uio"}])
                          form.setFieldValue(["users", key, "last"], [12, 23]);
                          // form.setFieldValue(
                          //   "users",
                          //   form
                          //     .getFieldValue("users")
                          //     .map((item: any, idx: any) => {
                          //       return key === idx
                          //         ? {
                          //             ...item,
                          //             last: [],
                          //           }
                          //         : item; // 如果索引匹配，则重置为初始值（这里以空字符串为例）
                          //     })
                          // );
                        }}
                        style={{ width: "300px" }}
                        placeholder="请选择平台"
                      >
                        {platFormList.map((item: any) => (
                          <Option
                            key={item?.id}
                            value={item?.id}
                            label={item?.description}
                          >
                            {item?.description}
                          </Option>
                        ))}
                      </Select>
                    </Form.Item>{" "}
                    <Form.Item {...restField} name={[name, "last"]}>
                      <Select
                        showSearch
                        mode="multiple"
                        allowClear
                        labelInValue
                        style={{ width: "300px" }}
                        optionLabelProp="label"
                        filterOption={false}
                        placeholder="请选择服务"
                      >
                        {searchFun(key, platFormList).map((item: any) => (
                          <Option
                            key={item?.id}
                            value={item?.id}
                            label={item?.serviceName}
                          >
                            {item?.serviceName}
                          </Option>
                        ))}
                      </Select>
                    </Form.Item>
                    <MinusCircleOutlined onClick={() => remove(name)} />
                  </Space>
                );
              })}
              <Form.Item>
                <Button
                  type="dashed"
                  onClick={() => add()}
                  block
                  icon={<PlusOutlined />}
                >
                  新增一项
                </Button>
              </Form.Item>
            </>
          )}
        </Form.List>
        <p>//【接口搜索数据。。。】</p>
        {/* <Form.List
          name="usersearch"
           
        >
          {(fields, { add, remove }) => (
            <>
              {fields.map(({ key, name, ...restField }) => {
                return (
                  <Space
                    key={key}
                    style={{ display: "flex", marginBottom: 8 }}
                    align="baseline"
                  >
                    <Form.Item
                      {...restField}
                      name={[name, "first"]}
                      rules={[{ required: true, message: "请选择" }]}
                    >
                      <Select
                       key={key}
                        allowClear
                        showSearch
                        optionFilterProp="children"
                        optionLabelProp="label"
                        onSearch={(value) => UserChangeSelect(value)}
                        labelInValue
                         
                        onChange={(value, item) => {
                         
                           
                        }}
                        style={{ width: "300px" }}
                        placeholder="请选择平台"
                      >
                        {testSelectListFirst?.map((item: any) => (
                          <Option
                            key={item?.id}
                            value={item?.id}
                            label={item?.siteName}
                          >
                            {item?.siteName}
                          </Option>
                        ))}
                      </Select>
                    </Form.Item>
                    <Form.Item {...restField} name={[name, "last"]}>
                      <Select
                        showSearch
                        mode="multiple"
                        allowClear
                        labelInValue
                        style={{ width: "300px" }}
                        optionLabelProp="label"
                        filterOption={false}
                        placeholder="请选择服务"
                      >
                        {searchFun(key, platFormList).map((item: any) => (
                          <Option
                            key={item?.id}
                            value={item?.id}
                            label={item?.serviceName}
                          >
                            {item?.serviceName}
                          </Option>
                        ))}
                      </Select>
                    </Form.Item>
                    <MinusCircleOutlined onClick={() => remove(name)} />
                  </Space>
                );
              })}
              <Form.Item>
                <Button
                  type="dashed"
                  onClick={() => add()}
                  block
                  icon={<PlusOutlined />}
                >
                  新增一项
                </Button>
              </Form.Item>
            </>
          )}
        </Form.List> */}
        <Form.Item>
          <Button type="primary" htmlType="submit">
            提交
          </Button>
        </Form.Item>
      </Form>
    </>
  );
};
